package com.heliang.service.info.impl;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import com.heliang.dataaccess.bean.AdvBean;
import com.heliang.dataaccess.bean.InfoBean;
import com.heliang.dataaccess.bean.InfoCatBean;
import com.heliang.dataaccess.bean.MailListBean;
import com.heliang.dataaccess.bean.VersionBean;
import com.heliang.dataaccess.dao.AdvBeanDao;
import com.heliang.dataaccess.dao.InfoCatDao;
import com.heliang.dataaccess.dao.InfoDao;
import com.heliang.dataaccess.dao.VersionDao;
import com.heliang.dataaccess.dao.impl.AdvertisementDaoimpl;
import com.heliang.dataaccess.dao.impl.InfoCatDaoImpl;
import com.heliang.dataaccess.dao.impl.InfoDaoImpl;
import com.heliang.dataaccess.dao.impl.VersionBeanDaoImpl;
import com.heliang.protocol.requestBean.ReqBodyAdvertisementBean;
import com.heliang.protocol.requestBean.ReqBodyIndexBean;
import com.heliang.protocol.responseBean.RspBodyAdvertisementBean;
import com.heliang.protocol.responseBean.RspBodyIndexBean;
import com.heliang.protocol.service.AdvertisementProtocolImpl;
import com.heliang.protocol.service.IndexProtocolImpl;
import com.heliang.service.BaseService;
import com.heliang.service.info.IndexService;
import com.heliang.util.AppUtil;
import com.heliang.util.Constants;
import com.heliang.util.Encry;
import com.hl.component.exception.DaoException;
import com.hl.component.exception.ErrorCode;
import com.hl.component.exception.ServiceException;
import com.hl.component.exception.handle.ExceptionHandle;

public class IndexServiceImpl extends BaseService implements IndexService {
    private InfoCatDao infoCatDao;
    private InfoDao infoDao;
    private VersionDao versionDao;
    private AdvBeanDao advDao;
    private String url = "";
    private RspBodyIndexBean rspBean;
    private RspBodyAdvertisementBean rspBodyAdvertisementBean = null;
    String keyvalue = Encry.md5s(Constants.SITE_ID + Constants.SECKEY);

    public IndexServiceImpl(Context context) {
        infoCatDao = new InfoCatDaoImpl(context);
        versionDao = new VersionBeanDaoImpl(context);
        infoDao = new InfoDaoImpl(context);
        advDao = new AdvertisementDaoimpl(context);
    }

    /**
     * 获取资讯类别
     * @return
     * @throws ServiceException
     */
    public List<InfoCatBean> getInfoCatList() throws ServiceException {
        List<InfoCatBean> infoCats;
        try {
            infoCats = infoCatDao.findAllInfoCats();
            return infoCats;
        } catch (DaoException e) {
            ExceptionHandle.throwServiceException(e, ErrorCode.SERVICE_QUERY_ERROR_004,
                "IndexServiceImpl.getInfoCatList " + "获取资讯类别信息失败！");
            return null;
        }
    }

    /**
     * 获取头部广告
     * @return
     */
    public List<AdvBean> getFooterAdvBeanList() throws ServiceException {
        List<AdvBean> advBeanList;
        try {
            advBeanList = advDao.queryFoot();
            return advBeanList;
        } catch (Exception e) {
            ExceptionHandle.throwServiceException(e, ErrorCode.SERVICE_QUERY_ERROR_004,
                "IndexServiceImpl.getFooterAdvBeanList " + "获取底部广告信息失败！");
            return null;
        }
    }

    /**
     * 获取头部广告
     * @return
     */
    public List<AdvBean> getTopAdvBeanList() throws ServiceException {
        List<AdvBean> advBeanList;
        try {
            advBeanList = advDao.queryTop();
            return advBeanList;
        } catch (Exception e) {
            ExceptionHandle.throwServiceException(e, ErrorCode.SERVICE_QUERY_ERROR_004,
                "IndexServiceImpl.getTopAdvBeanList " + "获取头部广告信息失败！");
            return null;
        }
    }

    /**
     * 获取新闻头条
     * @return
     */
    public List<InfoBean> getHeadBeanList(int type, int catId) throws ServiceException {
        List<InfoBean> infoBeanList;
        try {
            infoBeanList = infoDao.query(type, catId);
            return infoBeanList;
        } catch (Exception e) {
            ExceptionHandle.throwServiceException(e, ErrorCode.SERVICE_QUERY_ERROR_004,
                "IndexServiceImpl.getHeadBeanList " + "获取首页推荐资讯失败！");
            return null;
        }
    }

    /**
     * 获取活动的会员
     * @return
     */
    public List<MailListBean> getActiveMember() throws ServiceException {
        List<MailListBean> contactList = new ArrayList<MailListBean>();
        if (rspBean != null) {
            contactList = rspBean.getContactList();
        }
        return contactList;
    }

    /**
     * 修改资讯读取状态
     * @param id
     * @param isRead
     */
    public boolean updateReadStatus(InfoBean infoBean) throws ServiceException {
        try {
            return infoDao.updateInfoBean(infoBean);
        } catch (DaoException e) {
            ExceptionHandle.throwServiceException(e, ErrorCode.SERVICE_QUERY_ERROR_004,
                "IndexServiceImpl.updateReadStatus " + "修改资讯状态失败！");
            return false;
        }
    }

    @Override
    public void updateData() throws ServiceException {
        /********************************* 更新资讯类别和推荐资讯 *********************************/
        /* 获取当前客户端的资讯类别版本 */
        VersionBean infoCatVersion = new VersionBean();
        VersionBean recommendNewsVersion = new VersionBean();
        try {
            infoCatVersion = getClientInfoCatVersion();
            recommendNewsVersion = getClientRecommendNews();
        } catch (DaoException e) {
            ExceptionHandle.throwServiceException(e, ErrorCode.SERVICE_QUERY_ERROR_004,
                "IndexServiceImpl.getHeadBeanList " + "获取客户端资讯类别,推荐资讯版本失败！");
            infoCatVersion.setVer(0);
            recommendNewsVersion.setVer(0);
        }

        /* 获取服务器端资讯类别,推荐资讯版本 */
        boolean updateResult = getServerInfoCatAndRecomendVersion(infoCatVersion, recommendNewsVersion);
        if (updateResult && rspBean != null) {
            /* 更新资讯类别 */
            this.updateInfoCat(infoCatVersion);

            /* 更新推荐资讯 */
            this.updateRecommendNews(recommendNewsVersion);
        }

        /********************************* 广告位的更新 *********************************/
        /* 获取当前客户端推荐广告版本 */
        VersionBean advVersion = null;
        try {
            advVersion = versionDao.findVersionByVerId(Constants.VER_ADVERTISEMENT);
        } catch (DaoException e) {
            ExceptionHandle.throwServiceException(e, ErrorCode.SERVICE_QUERY_ERROR_004,
                "IndexServiceImpl.getHeadBeanList " + "获取客户端资讯类别,推荐资讯版本失败！");
        }

        /* 查询服务器端广告位的版本 */
        boolean getServerResult = this.getServerAdvVersion(advVersion);
        if(getServerResult && rspBodyAdvertisementBean != null){
            /* 更新广告 */
            this.updateAdvVersion(advVersion);
        }
    }

    /**
     * @Description: 查询当前客户端资讯类别版本
     * @param: @return
     * @param: @throws DaoException
     * @return: VersionBean
     * @throws
     * @author heliang
     * @Date 2013-11-4 上午3:01:16
     */
    public VersionBean getClientInfoCatVersion() throws DaoException {
        VersionBean infoCatVersion;
        infoCatVersion = versionDao.findVersionByVerId(Constants.VER_INFO_CAT);
        return infoCatVersion;
    }

    /**
     * @Description: 获取服务器端资讯类别,推荐资讯版本
     * @param: @param infoCatVersion
     * @param: @param recommendNewsVersion
     * @param: @throws ServiceException
     * @return: void
     * @throws
     * @author heliang
     * @Date 2013-11-4 上午2:59:42
     */
    public boolean getServerInfoCatAndRecomendVersion(VersionBean infoCatVersion,
                                                      VersionBean recommendNewsVersion)
        throws ServiceException {
        ReqBodyIndexBean reqBodyBaseBean = new ReqBodyIndexBean();
        reqBodyBaseBean.setVerInfoCat(infoCatVersion.getVer());
        reqBodyBaseBean.setVerNews(recommendNewsVersion.getVer());
        reqBodyBaseBean.setKeyValue(keyvalue);
        reqBodyBaseBean.setEdition(1);
        reqBodyBaseBean.setSiteId(Constants.SITE_ID);
        url += Constants.ACCESS_SERVICE_LINK + Constants.INTERFACE_INDEX;
        try {
            rspBean = (RspBodyIndexBean) IndexProtocolImpl.dataProcess(reqBodyBaseBean, url);
            return true;
        } catch (Exception e) {
            ExceptionHandle.throwServiceException(e, ErrorCode.SERVICE_QUERY_ERROR_004,
                "IndexServiceImpl.getServerInfoCatAndRecomendVersion " + "获取服务器端推荐资讯版本，和资讯类别版本格式化失败！");
            return false;
        }
    }

    /**
     * @Description: 查询服务器端广告位的版本
     * @param: @param advVersion
     * @return: void
     * @throws
     * @author heliang
     * @Date 2013-11-4 上午3:05:38
     */
    public boolean getServerAdvVersion(VersionBean advVersion) throws ServiceException {
        ReqBodyAdvertisementBean reqBodyAdvertisementBean = new ReqBodyAdvertisementBean();
        reqBodyAdvertisementBean.setKeyValue(keyvalue);
        reqBodyAdvertisementBean.setSiteId(Constants.SITE_ID);
        reqBodyAdvertisementBean.setVerAdv(advVersion.getVer());
        String urlAdv = Constants.ACCESS_SERVICE_LINK + Constants.INTERFACE_ADVERTISEMENT;
        try {
            rspBodyAdvertisementBean = (RspBodyAdvertisementBean) AdvertisementProtocolImpl.dataProcess(
                reqBodyAdvertisementBean, urlAdv);
            return true;
        } catch (Exception e) {
            ExceptionHandle.throwServiceException(e, ErrorCode.SERVICE_QUERY_ERROR_004,
                "IndexServiceImpl.getServerInfoCatAndRecomendVersion " + "获取服务器广告版本Json格式化失败！");
            return false;
        }

    }

    /**
     * @Description: 查询当前客户端推荐资讯版本
     * @param: @return
     * @param: @throws DaoException
     * @return: VersionBean
     * @throws
     * @author heliang
     * @Date 2013-11-4 上午3:00:54
     */
    public VersionBean getClientRecommendNews() throws DaoException {
        VersionBean recommendNewsVersion;
        recommendNewsVersion = versionDao.findVersionByVerId(Constants.VER_RECOMMEND_INFO);
        return recommendNewsVersion;
    }

    /**
     * @Description: 更新资讯类别
     * @param: @param newInfoCat
     * @param: @return
     * @return: boolean
     * @throws
     * @author heliang
     * @Date 2013-11-3 下午10:03:57
     */
    public boolean updateInfoCat(VersionBean infoCatVersion) throws ServiceException {
        try {
            int newInfoCatVer = 0;
            /* 对比服务器端资讯类别版本与客服端资讯类别版本 的高低 服务器高则客服端做更新,删除操作 一样高则不做操作 */
            if (rspBean != null) {
                newInfoCatVer = rspBean.getVerInfoCat();
            }

            if (newInfoCatVer > infoCatVersion.getVer()) {
                List<InfoCatBean> infoCats = rspBean.getInfoCatList();
                /* 删除服务器下发的资讯类别和服务器指定要删除的类别 */
                Integer[] ids = new Integer[infoCats.size()];
                List<InfoCatBean> infoCatInsert = new ArrayList<InfoCatBean>();
                for (int i = 0; i < ids.length; i++) {
                    InfoCatBean InfocatBean = infoCats.get(i);
                    ids[i] = InfocatBean.getId();
                    infoCatInsert.add(InfocatBean);
                }
                Integer[] infoCatDelIds = rspBean.getDelCatIds();
                if (infoCatDelIds != null) {
                    infoCatDao.deleteInfoCats(AppUtil.mergeIntArray(ids, infoCatDelIds));
                } else {
                    // 删除所有下发的记录
                    infoCatDao.deleteInfoCats(ids);
                }

                // 插入update的记录
                infoCatDao.saveInfoCats(infoCatInsert);
                if (infoCatVersion != null) {
                    infoCatVersion.setVer(newInfoCatVer);
                    versionDao.updateVersions(infoCatVersion);
                }
            }
            return true;
        } catch (DaoException e) {
            ExceptionHandle.throwServiceException(e, ErrorCode.SERVICE_QUERY_ERROR_004,
                "IndexServiceImpl.updateInfoCat " + "更新客户端资讯类别数据失败！");

            return false;
        }

    }

    /**
     * @Description: 更新推荐资讯
     * @param: @param newRecommendNewsVersion
     * @param: @return
     * @return: boolean
     * @throws ServiceException
     * @throws
     * @author heliang
     * @Date 2013-11-3 下午10:07:37
     */
    public boolean updateRecommendNews(VersionBean recommendNewsVersion) throws ServiceException {
        int newRecommendNewsVer = 0;
        if (rspBean != null) {
            newRecommendNewsVer = rspBean.getVerInfo();
        }

        if (newRecommendNewsVer > recommendNewsVersion.getVer()) {
            List<InfoBean> infos = rspBean.getInfoList();
            Integer[] infoIds = new Integer[infos.size()];
            for (int i = 0; i < infos.size(); i++) {
                InfoBean infoBean = infos.get(i);
                infoIds[i] = infoBean.getId();
            }
            Integer[] infoDelIds = rspBean.getInfoDelIds();
            try {
                if (infoDelIds != null) {
                    infoDao.delete(1, 0, AppUtil.mergeIntArray(infoIds, infoDelIds));
                } else {
                    infoDao.delete(1, 0, infoIds);// 删除所有下发的记录
                }

                // 保存下发的推荐资讯
                infoDao.saveInfos(infos);

                /* 保证首页只有3条推荐记录 */
                int n = infoDao.queryInfoCount(1, 0);
                if (n > 3) {
                    infoDao.deleteOldest(1, 0, n - 3);
                }

                /* 更新客服端推荐资讯版本 */
                if (recommendNewsVersion != null && newRecommendNewsVer > recommendNewsVersion.getVer()) {
                    recommendNewsVersion.setVer(newRecommendNewsVer);
                    versionDao.updateVersions(recommendNewsVersion);
                }
            } catch (DaoException e) {
                ExceptionHandle.throwServiceException(e, ErrorCode.SERVICE_QUERY_ERROR_004,
                    "IndexServiceImpl.updateRecommendNews " + "更新首页推荐资讯信息失败！");
                return false;
            }

        }
        return true;
    }

    /**
     * @Description: 更新广告信息
     * @param: @param advVersion
     * @param: @return
     * @return: boolean
     * @throws
     * @author heliang
     * @Date 2013-11-3 下午11:17:30
     */
    public boolean updateAdvVersion(VersionBean advVersion) throws ServiceException {
        /* 获取服务端下发的广告版本 */
        int AdvVer = advVersion.getVer();
        if (rspBodyAdvertisementBean != null) {
            AdvVer = rspBodyAdvertisementBean.getVerAdv();
        }

        try {
            if (AdvVer > advVersion.getVer()) {
                /* 处理头部广告 */
                advDao.deleteFoot(rspBodyAdvertisementBean.getPublishedfoot());
                advDao.saveFoot(rspBodyAdvertisementBean.getFoots());

                /* 处理底部广告 */
                advDao.deleteTop(rspBodyAdvertisementBean.getPublishedtop());
                advDao.saveTop(rspBodyAdvertisementBean.getTops());
            }

            /* 更新客服端广告版本 */
            if (advVersion != null && AdvVer > advVersion.getVer()) {
                advVersion.setVer(AdvVer);
                versionDao.updateVersions(advVersion);
            }
            return true;
        } catch (DaoException e) {
            ExceptionHandle.throwServiceException(e, ErrorCode.SERVICE_QUERY_ERROR_004,
                "IndexServiceImpl.updateAdvVersion " + "更新首页广告信息失败！");
            return false;
        }

    }

    @Override
    public void getMoreData() throws ServiceException {
        // TODO Auto-generated method stub

    }
    
    
}
